<template>
  <a-modal
    :width="1000"
    v-model:visible="state.visible"
    centered
    :maskClosable="false"
     :closable="false"
  >
     <div class="content_top" >
      <close-outlined style="cursor: pointer;" @click="cancel"/>
     </div>
    <div class="content">
      <a-tabs v-model:activeKey="activeKey">
        <a-tab-pane key="1" tab="从橱窗添加商品">
          <div class="box_chu">
            <div class="chu_top">
              <span style="margin-right: 10px">商品来源:</span>
              <a-select
                v-model:value="appid"
                show-search
                @search="handleSearch"
                :filter-option="false"
                @change="handleChange"
                :maxTagCount="20"
                placeholder="请选择商品"
                style="width: 260px"
              >
                <a-select-option
                  :value="item.appid"
                  v-for="(item, index) in topicList"
                  :key="index"
                  >{{ item.nickname }}</a-select-option
                >
              </a-select>

              <a-input
                v-model:value="queryWords"
                addon-before="商品名称/编码"
                placeholder="请输入商品名称/编码搜索"
                style="width: 300px; margin-left: 20px"
              />

              <a-button style="margin-left: 20px" @click="init">筛选</a-button>

              <a-button style="margin-left: 20px" type="link" @click="ReclearFn"
                ><redo-outlined />重置</a-button
              >
            </div>
            <div class="chu_table">
              <a-table
                :loading="tableLoading"
                :dataSource="dataSource"
                :columns="columns"
                @change="handleTableChange"
                :row-selection="{
                  type: 'checkbox',
                  selectedRowKeys: selectedRowKeys,
                  onChange: onSelectChange,
                }"
                rowKey="productId"
              >
                <template #bodyCell="{ column, record }">
                  <template v-if="column.key === 'info'">
                    <div
                      class="info_box tab_m20"
                      @click="selectFn(record)"
                      style="cursor: pointer;"
                    >
                      <div
                        class="left "
                        v-if="record.imgUrls && record.imgUrls.length > 0"
                      >
                        <img :src="record.imgUrls[0]" alt="" class="left_img" />
                      </div>
                      <div class="right">
                        <div class="right_top">{{ record.title }}</div>
                        <div
                          class="right_bottom"
                          v-if="record.productId"
                          @click.stop="copyfn(record.productId)"
                        >
                          商品编码: {{ record.productId }} <copy-outlined />
                        </div>
                      </div>
                    </div>
                  </template>

                  <template v-if="column.key === 'platformName'">
                    <div class="text_m20" @click="selectFn(record)" >
                      {{ record.platformName }}
                    </div>
                  </template>

                  <template v-if="column.key === 'sellingPrice'">
                    <div class="text_m20" @click="selectFn(record)" >
                      {{ record.sellingPrice }}
                    </div>
                  </template>

                  <template v-if="column.key === 'stock'">
                    <div  class="text_m20" @click="selectFn(record)">
                      {{ record.stock }}
                    </div>
                  </template>
                </template>
              </a-table>
            </div>
          </div>
        </a-tab-pane>
        <!-- <a-tab-pane key="2" tab="商品链接导入">
          <a-textarea
            v-model:value="value2"
            placeholder="请粘贴带货商品链接或编号，支持批量粘贴， 请用英文逗号','或换行隔开, 一次最多可识别30个链接"
          />

          <a-button style="margin-top: 20px">识别链接</a-button>
        </a-tab-pane> -->
      </a-tabs>
    </div>

    <template #footer>
      <a-button :disabled="tableLoading" key="back" @click="cancel">取消</a-button>
      <a-button :disabled="tableLoading" key="submit" type="primary" @click="subitfn">确定</a-button>
    </template>
  </a-modal>
</template>

<script setup>
import { ref, reactive, defineEmits, defineProps, computed, h } from "vue";
import {
  SmileOutlined,
  MehOutlined,
  RedoOutlined,
  CopyOutlined,
  CloseOutlined
} from "@ant-design/icons-vue";
import request from "@/common/utils/request";
import { message } from "ant-design-vue";
const props = defineProps({});
const emit = defineEmits(["success"]);
const columns = ref([
  {
    title: "商品信息",
    dataIndex: "info",
    key: "info",
    width: 400,
  },
  {
    title: "商品来源",
    dataIndex: "platformName",
    key: "platformName",
  },
  {
    title: "价格",
    dataIndex: "sellingPrice",
    key: "sellingPrice",
  },
  {
    title: "库存",
    dataIndex: "stock",
    key: "stock",
  },
]);

const selectedRowKeys = ref([]);

const dataSource = ref([
  // {
  //   id: 1,
  //   imgUrls: [
  //     "https://store.mp.video.tencent-cloud.com/161/20304/snscosdownload/SH/reserved/6465cd3300093e931770bc8ca90d8b0b000000a000004f50?imageView2/1/w/800/h/800/q/50",
  //   ],
  //   showBoxItems: [],
  //   iconUrls: [],
  //   belowTitleBlocks: [],
  //   belowTitleBlocksBside: [],
  //   iconTags: [],
  //   coupons: [],
  //   productIconTags: [],
  //   productId: "10000040116821",
  //   title: "AI智能机器人软件",
  //   stock: 1995,
  //   marketPrice: 3990,
  //   sellingPrice: 3990,
  //   status: 1,
  //   platformName: "快鲸AI",
  //   halfPage: {
  //     appid: "wxca8d4b8e8feedc2a",
  //     path: "main/channels/buy/buy.html?productId=10000040116820&realappid=wx513e2597bbaa725f",
  //     headimgUrl:
  //       "http://mmbiz.qpic.cn/mmbiz_jpg/XEAUldCBHotfcytofdvd4JlphOqNyu5Yu1V1DQLPLO3PP32HJTzgCSdEKuprUCjoIX8f1HNcU5WIFTvwelrkog/0?wx_fmt=jpeg/0",
  //     nickname: "快鲸AI",
  //   },
  //   fullPage: {
  //     appid: "wxca8d4b8e8feedc2a",
  //     path: "main/pages/productDetail/productDetail.html?productId=10000040116820&realappid=wx513e2597bbaa725f",
  //     headimgUrl:
  //       "http://mmbiz.qpic.cn/mmbiz_jpg/XEAUldCBHotfcytofdvd4JlphOqNyu5Yu1V1DQLPLO3PP32HJTzgCSdEKuprUCjoIX8f1HNcU5WIFTvwelrkog/0?wx_fmt=jpeg/0",
  //     nickname: "快鲸AI",
  //   },
  //   noSale: 0,
  //   appid: "wx513e2597bbaa725f",
  //   isCarryingProduct: 0,
  //   sales: 5,
  //   outProductId: "10000040116820",
  //   isShelfProduct: 1,
  //   thirdCategoryId: "529047",
  //   noSaleInfo: {
  //     categoryWording: "",
  //     noSaleStatus: 0,
  //   },
  //   isHideForWindow: 1,
  //   productType: 9,
  //   canRemove: 0,
  //   previewPage: {
  //     appid: "wxca8d4b8e8feedc2a",
  //     path: "main/pages/productDetail/productDetail.html?productId=10000040116820&realappid=wx513e2597bbaa725f",
  //     headimgUrl:
  //       "http://mmbiz.qpic.cn/mmbiz_jpg/XEAUldCBHotfcytofdvd4JlphOqNyu5Yu1V1DQLPLO3PP32HJTzgCSdEKuprUCjoIX8f1HNcU5WIFTvwelrkog/0?wx_fmt=jpeg/0",
  //     nickname: "快鲸AI",
  //   },
  //   productArea: 0,
  //   customSortOrder: "9232379236110936800",
  //   leagueRule: [],
  //   reminderContentType: 1,
  //   giftActivityInfo: {
  //     productImgUrls: [],
  //   },
  //   previewPageParam: {
  //     productSource: 4,
  //   },
  // },
  // {
  //   id: 2,
  //   imgUrls: [
  //     "https://store.mp.video.tencent-cloud.com/161/20304/snscosdownload/SH/reserved/6465cd3300093e931770bc8ca90d8b0b000000a000004f50?imageView2/1/w/800/h/800/q/50",
  //   ],
  //   showBoxItems: [],
  //   iconUrls: [],
  //   belowTitleBlocks: [],
  //   belowTitleBlocksBside: [],
  //   iconTags: [],
  //   coupons: [],
  //   productIconTags: [],
  //   productId: "10000040116820",
  //   title: "AI智能机器人软件",
  //   stock: 1995,
  //   marketPrice: 3990,
  //   sellingPrice: 3990,
  //   status: 1,
  //   platformName: "快鲸AI",
  //   halfPage: {
  //     appid: "wxca8d4b8e8feedc2a",
  //     path: "main/channels/buy/buy.html?productId=10000040116820&realappid=wx513e2597bbaa725f",
  //     headimgUrl:
  //       "http://mmbiz.qpic.cn/mmbiz_jpg/XEAUldCBHotfcytofdvd4JlphOqNyu5Yu1V1DQLPLO3PP32HJTzgCSdEKuprUCjoIX8f1HNcU5WIFTvwelrkog/0?wx_fmt=jpeg/0",
  //     nickname: "快鲸AI",
  //   },
  //   fullPage: {
  //     appid: "wxca8d4b8e8feedc2a",
  //     path: "main/pages/productDetail/productDetail.html?productId=10000040116820&realappid=wx513e2597bbaa725f",
  //     headimgUrl:
  //       "http://mmbiz.qpic.cn/mmbiz_jpg/XEAUldCBHotfcytofdvd4JlphOqNyu5Yu1V1DQLPLO3PP32HJTzgCSdEKuprUCjoIX8f1HNcU5WIFTvwelrkog/0?wx_fmt=jpeg/0",
  //     nickname: "快鲸AI",
  //   },
  //   noSale: 0,
  //   appid: "wx513e2597bbaa725f",
  //   isCarryingProduct: 0,
  //   sales: 5,
  //   outProductId: "10000040116820",
  //   isShelfProduct: 1,
  //   thirdCategoryId: "529047",
  //   noSaleInfo: {
  //     categoryWording: "",
  //     noSaleStatus: 0,
  //   },
  //   isHideForWindow: 1,
  //   productType: 9,
  //   canRemove: 0,
  //   previewPage: {
  //     appid: "wxca8d4b8e8feedc2a",
  //     path: "main/pages/productDetail/productDetail.html?productId=10000040116820&realappid=wx513e2597bbaa725f",
  //     headimgUrl:
  //       "http://mmbiz.qpic.cn/mmbiz_jpg/XEAUldCBHotfcytofdvd4JlphOqNyu5Yu1V1DQLPLO3PP32HJTzgCSdEKuprUCjoIX8f1HNcU5WIFTvwelrkog/0?wx_fmt=jpeg/0",
  //     nickname: "快鲸AI",
  //   },
  //   productArea: 0,
  //   customSortOrder: "9232379236110936800",
  //   leagueRule: [],
  //   reminderContentType: 1,
  //   giftActivityInfo: {
  //     productImgUrls: [],
  //   },
  //   previewPageParam: {
  //     productSource: 4,
  //   },
  // },
]);
const state = reactive({
  visible: false,
  pageInfo: {
    page: 1,
    pageSize: 10,
    total: 0,
  },
  value2: "",
  only_id: "",
});

const checkedID = ref("");
const activeKey = ref("1");
const queryWords = ref("");
const tableLoading = ref(false);

const showModal = (info) => {
  state.only_id = info.id;
  state.visible = true;
  checkedID.value = info.productId;
  getsearch();
  init();
};
const topicList = ref([]);
const appid = ref("");

const getsearch = () => {
  request
    .get("/work_ai", "/platform/account/with/shopList", {
      id: state.only_id,
    })
    .then((res) => {
      topicList.value = res.result.shopItemList;

       topicList.value.unshift({
        nickname: "全部",
        appid: "all",
      });

      topicList.value.push({
        nickname: "带货商品",
        appid: "fromOtherShopOnly",
      });
    })
    .catch((err) => {
      message.error("操作失败");
    });
};


const cancel = () => {
  if (tableLoading.value) {
    return message.warning("请稍等")
  } else {
  state.visible = false;
  state.only_id = "";
  appid.value = "";
  queryWords.value = "";
  selectedRowKeys.value = [];
  }
 
};

const init = () => {
  let fromOtherShopOnly;
  let re_app_id;
  if (appid.value == "fromOtherShopOnly") {
    re_app_id = "";
    fromOtherShopOnly = "1";
  } else if (appid.value == "all") {
     re_app_id = "";
    fromOtherShopOnly = "";
  } else {
    re_app_id = appid.value;
    fromOtherShopOnly = "";
  }
  tableLoading.value = true;
  request
    .get("/work_ai", "/platform/account/all/products", {
      id: state.only_id,
      appid: re_app_id,
      fromOtherShopOnly: fromOtherShopOnly,
      queryWords: queryWords.value,
      pageSize: state.pageInfo.pageSize,
      page: state.pageInfo.page,
    })
    .then((res) => {
      tableLoading.value = false;
      dataSource.value = res.result.products;
      if (checkedID.value !== "") {
        selectedRowKeys.value.push(checkedID.value);
      }
    });
};

const handleTableChange = ({ current, pageSize }) => {
  state.pageInfo.pageSize = pageSize;
  state.pageInfo.page = current;
  init();
};

const onSelectChange = (item) => {
  if (item.length > 1) {
    message.warning("只能选择一个商品");
    selectedRowKeys.value = [];
    selectedRowKeys.value.push(item[item.length - 1]);
  } else {
    selectedRowKeys.value = item;
  }
};

const subitfn = () => {
  if (activeKey.value == "1") {
    const matchedItem = dataSource.value.find((item) =>
      selectedRowKeys.value.includes(item.productId)
    );

    emit("success", { matchedItem: matchedItem, account_id: state.only_id });
    cancel();
  }
};

const ReclearFn = () => {
  appid.value = "";
  queryWords.value = "";
  init()

};

const copyfn = async (textToCopy) => {
  try {
    await navigator.clipboard.writeText(textToCopy);
    message.success("商品编码已复制到剪贴板");
  } catch (err) {
    message.error("复制失败，请重试");
  }
};

const selectFn = (data) => {
  if (data.productId == selectedRowKeys.value[0]) {
    return (selectedRowKeys.value = []);
  }

  if (selectedRowKeys.value.length == 1) {
    // message.warning("只能选择一个商品");
    selectedRowKeys.value = [];
    selectedRowKeys.value.push(data.productId);
  } else {
    selectedRowKeys.value.push(data.productId);
  }
};
defineExpose({
  showModal,
  cancel,
});
</script>

<style lang="less">
.ss-modal-content {
  border-radius: 10px !important;
}

.ss-table-tbody>tr>td {
  // padding: 0px !important;
}


</style>

<style lang="less" scoped>
.cascader {
  :deep(.ss-cascader-menus) {
    padding: 20px;
    &::-webkit-scrollbar {
      width: 8px; /* 滚动条的宽度 */
      height: 10px; /* 滚动条的高度，垂直滚动条可能用得上 */
      display: none;
    }
    &::-webkit-scrollbar-thumb {
      background: #eeeeee; /* 滑块的背景颜色 */
      border-radius: 10px; /* 滑块的圆角 */
    }
  }
  :deep(.ss-cascader-menu) {
    height: 100%;
    &:nth-child(1) {
      max-height: 400px;
      width: 130px;
      overflow-y: auto;
      .ss-cascader-menu-item-content {
        padding: 5px;
      }
      .ss-cascader-menu-item-active {
        color: var(--ss-primary-color);
      }
      &::-webkit-scrollbar {
        width: 8px; /* 滚动条的宽度 */
        height: 10px; /* 滚动条的高度，垂直滚动条可能用得上 */
        display: none;
      }
      &::-webkit-scrollbar-thumb {
        background: #eeeeee; /* 滑块的背景颜色 */
        border-radius: 10px; /* 滑块的圆角 */
      }
    }
    &:nth-child(2) {
      width: 400px;
      max-height: 400px;
      overflow-y: auto;
      .ss-cascader-menu-item-active {
        color: var(--ss-primary-color);
      }
      .ss-cascader-menu-item-content {
        width: 100%;
        padding: 5px;
        white-space: nowrap; /* 强制文本在一行显示 */
        overflow: hidden; /* 隐藏溢出部分 */
        text-overflow: ellipsis; /* 用省略号表示溢出部分 */
      }
      .ss-cascader-menu-item-expand .ss-cascader-menu-item-expand-icon,
      .ss-cascader-menu-item-loading-icon {
        display: none;
      }
      &::-webkit-scrollbar {
        width: 8px; /* 滚动条的宽度 */
        height: 10px; /* 滚动条的高度，垂直滚动条可能用得上 */
        display: none;
      }
      &::-webkit-scrollbar-thumb {
        background: #eeeeee; /* 滑块的背景颜色 */
        border-radius: 10px; /* 滑块的圆角 */
      }
    }
    // &:nth-child(3) {
    //   width: 300px;
    //   max-height: 400px;
    //   overflow-y: auto;
    //   color: #999;
    //   .ss-cascader-menu-item-active {
    //     color: var(--ss-primary-color);
    //   }
    //   .ss-cascader-menu-item-content {
    //     width: 100%;
    //     padding: 5px;
    //     white-space: nowrap; /* 强制文本在一行显示 */
    //     overflow: hidden; /* 隐藏溢出部分 */
    //     text-overflow: ellipsis; /* 用省略号表示溢出部分 */
    //   }
    //   &::-webkit-scrollbar {
    //     width: 8px; /* 滚动条的宽度 */
    //     height: 10px; /* 滚动条的高度，垂直滚动条可能用得上 */
    //     display: none;
    //   }
    //   &::-webkit-scrollbar-thumb {
    //     background: #eeeeee; /* 滑块的背景颜色 */
    //     border-radius: 10px; /* 滑块的圆角 */
    //   }
    // }
  }
}
.tag-select {
  position: relative;
  .tip_text {
    position: absolute;
    right: 0;
    bottom: 0;
    color: #858585;
    padding: 5px;
  }
}

.content {
  height: 600px;
  overflow-y: auto;

  .chu_table {
    margin-top: 20px;
    .info_box {
      display: flex;
      align-items: center;
      .left {
        .left_img {
          width: 80px;
          height: 80px;
          border-radius: 6px;
        }
      }

      .right {
        margin-left: 10px;
        .right_bottom {
          color: #ccc;
          cursor: pointer;
        }
      }
    }
  }
}

.tab_m20 {
  padding: 20px;
}

.text_m20 {
  height: 120px;
  width: 100%;
  display: flex;
  // justify-content: center;
  margin-left: 20px;
  align-items: center;
  cursor: pointer;
}

.content_top {
font-size: 18px;
  display: flex;
  justify-content: flex-end;
  
}
</style>
